#!/usr/bin/env python3
#识别当前文件夹中名字以.app结尾的文件夹
import os
import openpyxl
import sys

#在当前文件中搜索.ipa文件,使用-unzip 解压.ipa文件,取出Payload中的.app放到当前文件夹中
def find_ipa_files(directory):
    ipa_files = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.ipa'):
                ipa_files.append(os.path.join(root, file))  # 保存完整路径
    return ipa_files    #返回ipa文件列表
#解压ipa文件
def unzip_ipa(ipa_file):
    # 解压IPA文件
    os.system(f'unzip -q {ipa_file} -d {os.path.dirname(ipa_file)}')
    print(f"解压完成: {ipa_file}")  # 输出提示信息
#在解压出来的文件中找到.app文件,移动到最上层目录
def move_app_files(directory):
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.app'):
                # 移动.app文件到最上层目录
                os.system(f'mv {os.path.join(root, file)} {directory}')

def find_app_folders(directory):
    app_folders = []
    for root, dirs, files in os.walk(directory):
        for dir in dirs:
            if dir.endswith('.app'):
                app_folders.append(os.path.join(root, dir))
    return app_folders



#在app_folders遍历所有的文件,识别以.bundle.framework结尾的文件,把文件名写入到targetSDK.xlsx的第一列
def find_bundle_frameworks(app_folders):
    file_prefixes = set()
    for app_folder in app_folders:
        for root, dirs, files in os.walk(app_folder):
            # 检测以.framework/.bundle结尾的目录
            if root.endswith(('.framework', '.bundle')):
                prefix = os.path.basename(root).split('.')[0].lower()
                file_prefixes.add(prefix)
            
            # 检测以.bundle或者.framework结尾的文件
            for filename in files:
                if filename.endswith('.bundle.framework'):
                    prefix = filename.split('.')[0].lower()
                    file_prefixes.add(prefix)
    return file_prefixes


#把bundle_frameworks写入到targetSDK.xlsx的第一列
def write_to_excel(file_path, data):
    wb = openpyxl.Workbook()
    ws = wb.active
    #检查row1cloumn1 的值是否为name,如果不是则写入name
    if ws.cell(row=1, column=1).value!= 'name':
        ws.cell(row=1, column=1).value = 'name'
    if ws.cell(row=1, column=2).value!= 'isThirdLib':
        ws.cell(row=1, column=2).value = 'isThirdLib'
    if ws.cell(row=1, column=3).value!= 'HomePageLink':
        ws.cell(row=1, column=3).value = 'HomePageLink'

    for item in data:
        ws.append([item])  # 写入数据
    wb.save(file_path)
    print(f"数据已写入到 {file_path}")  # 输出提示信息
# 调用函数
def main():
    directory = '.'
    os.chmod(__file__, 0o755)  # 自动添加执行权限
    ipa_files = find_ipa_files(directory)
    
    if not ipa_files:
        print("未找到.ipa文件")
        sys.exit(1)
    
    unzip_ipa(ipa_files[0])
    move_app_files(directory)
    app_folders = find_app_folders(directory)
    names = find_bundle_frameworks(app_folders)
    write_to_excel('targetSDK.xlsx', names)

if __name__ == '__main__':
    main()
